package cn.senjoeson.triper.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.senjoeson.mylibrary.base.MyBaseAdapter;
import cn.senjoeson.mylibrary.utils.DisplayUtils;
import cn.senjoeson.mylibrary.utilschanged.LogUtils;
import cn.senjoeson.mylibrary.utilschanged.MyToast;
import cn.senjoeson.triper.R;
import cn.senjoeson.triper.activity.SelectTimeActivity;
import cn.senjoeson.triper.activity.TripContentActivity;
import cn.senjoeson.triper.adapter.TripContentAdapter;
import cn.senjoeson.triper.base.GreenDaoManager;
import cn.senjoeson.triper.base.LazyFragment;
import cn.senjoeson.triper.bean.PlaceBean;
import cn.senjoeson.triper.bean.Plan;
import cn.senjoeson.triper.dao.PlaceBeanDao;
import cn.senjoeson.triper.utils.DateCalcUtils;
import cn.senjoeson.triper.utils.IdsUtils;


/**
 * @author Android
 * @date 2018/1/3
 */

public class BaseTripContentFragment extends LazyFragment implements TripContentActivity.OnTimeClickListener, TripContentActivity.OnOrderClickListener, TripContentActivity.OnMapClickListener, TripContentAdapter.OnChangeListener {

    @BindView(R.id.theday)
    TextView mTheday;
    @BindView(R.id.date)
    TextView mDate;
    @BindView(R.id.week)
    TextView mWeek;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    public String mCurrentDay;
    public PlaceBeanDao mPlaceBeanDao;
    public TripContentAdapter mTripContentAdapter;
    private boolean flag;
    public long mPlanId;


    private void getActivityParams() {
        String[] argments = getArguments().getStringArray("argment");
        mPlanId = getArguments().getLong("planId");
        if (argments != null) {
            String startDate = argments[0]; //该计划的第一天
            //代表第几天的意思
            mCurrentDay = argments[1];

            mTheday.setText(Html.fromHtml("<big>Day " + mCurrentDay + "</big>"));
            String currenetDate = DateCalcUtils.getCalcDate(startDate, Integer.parseInt(mCurrentDay));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            try {
                Date date = format.parse(currenetDate);
                String format1 = simpleDateFormat.format(date);
                mDate.setText(format1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            mWeek.setText(DateCalcUtils.getWeek(currenetDate));


        } else {
            LogUtils.d("获取的数据是空的！！");
        }
    }


    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(container.getContext(), R.layout.basefragment_trip_content, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        getActivityParams();
        mPlaceBeanDao = GreenDaoManager.getInstance().getNewSession().getPlaceBeanDao();
        LogUtils.d("当前的天数:" + mCurrentDay);
        PlaceBean depart = new PlaceBean(10001 + Long.parseLong(mCurrentDay) * 1000, mPlanId, Long.parseLong(mCurrentDay), "09:00", "Depart", "", 0, 0, true);
        PlaceBean lunch = new PlaceBean(10002 + Long.parseLong(mCurrentDay) * 1000, mPlanId, Long.parseLong(mCurrentDay), "12:00", "Lunch", "", 0, 0, true);
        PlaceBean dinner = new PlaceBean(10003 + Long.parseLong(mCurrentDay) * 1000, mPlanId, Long.parseLong(mCurrentDay), "18:00", "Dinner", "", 0, 0, true);
        PlaceBean aReturn = new PlaceBean(10004 + Long.parseLong(mCurrentDay) * 1000, mPlanId, Long.parseLong(mCurrentDay), "22:00", "Return", "", 0, 0, true);
        insertIngoreError(depart);
        insertIngoreError(lunch);
        insertIngoreError(dinner);
        insertIngoreError(aReturn);


        List<PlaceBean> list = getPlaceBeans();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mTripContentAdapter = new TripContentAdapter(getContext());
        mTripContentAdapter.setDatas(list);
        mRecyclerView.setAdapter(mTripContentAdapter);
        initListener();

    }

    private List<PlaceBean> getPlaceBeans() {
        return mPlaceBeanDao.queryBuilder()
                .where(PlaceBeanDao.Properties.Dayid.eq(mCurrentDay))
                .where(PlaceBeanDao.Properties.Planid.eq(mPlanId))
                .orderAsc(PlaceBeanDao.Properties.Time).build().list();
    }

    private void insertIngoreError(PlaceBean depart) {
        if (mPlaceBeanDao.load(depart.getId()) == null) {
            mPlaceBeanDao.insert(depart);
        }
    }


    private void makeOrder() {
        List<PlaceBean> list = null;
        if (!flag) {
            list = mPlaceBeanDao.queryBuilder()
                    .where(PlaceBeanDao.Properties.Dayid.eq(mCurrentDay))
                    .where(PlaceBeanDao.Properties.Planid.eq(mPlanId))
                    .orderAsc(PlaceBeanDao.Properties.Time).build().list();
            flag = true;
        } else {
            list = mPlaceBeanDao.queryBuilder()
                    .where(PlaceBeanDao.Properties.Dayid.eq(mCurrentDay))
                    .where(PlaceBeanDao.Properties.Planid.eq(mPlanId))
                    .orderDesc(PlaceBeanDao.Properties.Time).build().list();
            flag = false;
        }
        mTripContentAdapter.setDatas(list);
        mTripContentAdapter.notifyDataSetChanged();
        MyToast.showToast(flag ? "正序" : "倒序");
    }

    protected void initListener() {
        ((TripContentActivity) getActivity()).setOnTimeClickListener(this);
        ((TripContentActivity) getActivity()).setOnOrderClickListener(this);
        ((TripContentActivity) getActivity()).setOnMapClickListener(this);
        mTripContentAdapter.setOnChangeListener(this);
    }

    /**
     * 选择早中晚餐 时间
     */
    private void toSelectTime() {
        Intent intent = new Intent(getContext(), SelectTimeActivity.class);
        String conotent = mTheday.getText().toString().trim();
        long parseLong = Long.parseLong(conotent.replace("Day ", ""));
        LogUtils.d(parseLong + "");//Long.parseLong(mCurrentDay)
        intent.putExtra("dayId", parseLong);
        intent.putExtra("planId", mPlanId);
        startActivity(intent);
    }


    @Override
    public void onTimeClick(View view) {
        toSelectTime();
    }

    @Override
    public void onOrderClick(View view) {
        LogUtils.d("排序");
        makeOrder();
    }

    @Override
    public void onMapClick(View view) {
        MyToast.showToast("暂时不实现");
    }

    /**
     * 选择该地点在哪一天游玩
     *
     * @param placeBean       地点
     * @param adapterPosition 当前位置
     */
    @Override
    public void onChange(PlaceBean placeBean, int adapterPosition) {
        showChangeDialog(placeBean);
    }

    /**
     * 添加到某天
     *
     * @param placeBean
     */
    private void showChangeDialog(final PlaceBean placeBean) {
        final Dialog dialog = new Dialog(getContext());
        Window window = dialog.getWindow();
        WindowManager.LayoutParams windowparams = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        Rect rect = new Rect();
        View view1 = window.getDecorView();
        view1.getWindowVisibleDisplayFrame(rect);
        windowparams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        windowparams.width = DisplayUtils.getScreenWidthPixels(getActivity()) / 2;

        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setAttributes(windowparams);

        View view = LayoutInflater.from(getContext()).inflate(R.layout.change_day_dialog, null);

        ListView listView = view.findViewById(R.id.listview);
        final long planId = getActivity().getIntent().getLongExtra("planId", -1);
        Plan load = GreenDaoManager.getInstance().getNewSession().getPlanDao().load(planId);
        final int days = load.getDays();
        final ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < days; i++) {
            list.add("DAY " + (i + 1));
        }
        listView.setAdapter(new MyBaseAdapter<String>(list) {
            @SuppressLint("ViewHolder")
            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.simple_textview, null);
                TextView textView = convertView.findViewById(R.id.textview);

                textView.setText(mDataSets.get(position));
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (placeBean.getDayid() == position + 1) {
                            MyToast.showToast("当前已经是第" + (position + 1) + "天了哦!!");
                            return;
                        }
                        PlaceBeanDao placeBeanDao = GreenDaoManager.getInstance().getNewSession().getPlaceBeanDao();
                        LogUtils.d("更新之前" + placeBean.getId());
                        LogUtils.d("更新之前" + placeBean.getDayid());
                        mTripContentAdapter.deleteItem(placeBean);
                        PlaceBean newPlaceBean = new PlaceBean();
                        int day = position + 1;
                        long foodrinkId = IdsUtils.getOriginId(placeBean.getId(), placeBean.getPlanid(), placeBean.getDayid());
                        LogUtils.d("原始的fookid" + foodrinkId);
                        newPlaceBean.setDayid(day);
                        newPlaceBean.setPlanid(placeBean.getPlanid());
                        newPlaceBean.setId(IdsUtils.setPlaceIds(foodrinkId, placeBean.getPlanid(), day));
                        newPlaceBean.setTime(placeBean.getTime());
                        newPlaceBean.setImageUrl(placeBean.getImageUrl());
                        newPlaceBean.setPlaceName(placeBean.getPlaceName());
                        newPlaceBean.setFlag(placeBean.getFlag());
                        newPlaceBean.setStar(placeBean.getStar());
                        newPlaceBean.setStayTime(placeBean.getStayTime());

                        LogUtils.d("更新之后的id:" + newPlaceBean.getId());
                        if (placeBeanDao.load(newPlaceBean.getId()) == null) {
                            placeBeanDao.deleteByKey(placeBean.getId());
                            placeBeanDao.insert(newPlaceBean);
                        }
                        /*int day = position + 1;
                        long temp = placeBean.getId() - placeBean.getDayid() * 1000-day;
                        placeBean.setId(temp + day * 1000+day);
                        LogUtils.d("修改之后的placeid"+placeBean.getId());
                        placeBean.setDayid(position+1);
                        placeBeanDao.update(placeBean);*/
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                });
                return convertView;

            }
        });
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

    }

}
